package com.lfp.config.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 基于延时队列插件的 配置文件
 *
 *   队列关系参考./images下
 *      基于延时插件队列关系.png
 *
 * @Author lfp
 * @Date 2022/7/18
 * @Version 1.0
 */
@Configuration
public class DelayedQueueConfig {
    //交换机名
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    //队列名
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    //路由键
    public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";


    //声明 基于插件的，自定义交换机
    //注意交换机类型x-delayed-message 和 参数x-delayed-type:direct
    @Bean
    public CustomExchange delayedExchange(){
        Map<String,Object> arguments = new HashMap<>();
        arguments.put("x-delayed-type","direct");

        return new CustomExchange(
                DELAYED_EXCHANGE_NAME,//交换机名
                "x-delayed-message",//交换机类型（插件支持的类型）
                true,
                false,
                arguments
        );
    }

    //声明队列
    @Bean
    public Queue delayedQueue(){
        //return new Queue(DELAYED_QUEUE_NAME);
        return QueueBuilder.durable(DELAYED_QUEUE_NAME).build();
    }

    //绑定 将交换机绑定到延时交换机
    @Bean
    public Binding delayedQueueBindgingToDelayedExchange(@Qualifier("delayedQueue") Queue delayedQueue,
                                                         @Qualifier("delayedExchange") CustomExchange delayedExchange){

        //通过路由键，将队列delayedQueue 绑定到延迟交换机delayedExchange
        return BindingBuilder.
                bind(delayedQueue).
                to(delayedExchange).
                with(DELAYED_ROUTING_KEY)
                .noargs();//无需参数
    }

}
